import type { Next, Context } from 'koa';
import knex from '../utils/knex';

/**
 * @api {get} /dictItem/retrieve 查询字典项
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName retrieve
 * @apiGroup 字典项管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     label      字典标签【非必填】
 * @apiParam {String}     type       字典类型【非必填】
 * @apiParam {String}     startTime  字典项创建时间-开始【非必填】
 * @apiParam {String}     endTime    字典项创建时间-结束【非必填】
 * @apiParam {String}     status     字典状态 (0:正常 1:停用)【非必填】
 *
 * @apiUse RequestHeader
 * @apiUse dictItemRetrieveSuccess
 * @apiUse RequestError
 */
async function retrieveAction(ctx: Context, next: Next) {
    const { page = 1, size = 10, label = '', type = '', status, startTime = '', endTime = '' } = ctx.query;
    const whereObj: Record<string, any> = {};

    if (label) {
        whereObj.label = ['like', `%${label}%`];
    }
    if (type) {
        whereObj.type = type;
    }
    if (status) {
        whereObj.status = status;
    }
    if (startTime && endTime) {
        whereObj.create_time = ['between', startTime, endTime];
    }
    try {
        const data = await knex('sys_dict_item')
            .where(whereObj)
            .offset(((page as number) - 1) * (size as number))
            .limit(size as number)
            .select('*');
        const [count] = await knex('sys_dict_item').where(whereObj).count();
        ctx.success(
            {
                data,
                count: Object.values(count)[0],
            },
            '查询成功',
        );
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {post} /dictItem/add 新增字典项
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName add
 * @apiGroup 字典项管理
 *
 * @apiParam {String}  label     字典标签【必填】
 * @apiParam {String}  type      字典类型【必填】
 * @apiParam {String}  value     字典键值【必填】
 * @apiParam {String}  remark    备注【必填】
 * @apiParam {String}  status    字典状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse addSuccess
 * @apiUse RequestError
 */
async function addAction(ctx: Context, next: Next) {
    const { label = '', type = '', value = '', status = '', remark = '' } = ctx.request.body;
    try {
        await knex('sys_dict_item').insert({
            label: label,
            type: type,
            value: value,
            status: status,
            remark: remark,
        });
        ctx.success('', '新增成功');
    } catch (e) {
        ctx.fail(500, '新增失败  ' + e);
    }
    return next();
}

/**
 * @api {delete} /dictItem/delete 删除字典项
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName delete
 * @apiGroup 字典项管理
 *
 * @apiParam {int}     id    菜单id【必填】
 * @apiParam {String}  type  字典类型【必填】
 *
 * @apiUse RequestHeader
 * @apiUse deleteSuccess
 * @apiUse RequestError
 */
async function deleteAction(ctx: Context, next: Next) {
    const { id } = ctx.request.body;
    try {
        await knex('sys_dict_item').where({ id: id }).delete();
        ctx.success('', '删除成功');
    } catch (e: any) {
        ctx.fail(500, e.toString());
    }
    return next();
}

/**
 * @api {put} /dictItem/update 修改字典项
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName update
 * @apiGroup 字典项管理
 *
 * @apiParam {int}     id        字典id【必填】
 * @apiParam {String}  label     字典标签【必填】
 * @apiParam {String}  type      字典类型【必填】
 * @apiParam {String}  value     字典键值【必填】
 * @apiParam {String}  remark    备注【必填】
 * @apiParam {String}  status    字典状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse updateSuccess
 * @apiUse RequestError
 */
async function updateAction(ctx: Context, next: Next) {
    const { id, dictId, label = '', type = '', value = '', status, remark = '' } = ctx.request.body;
    try {
        await knex('sys_dict_item').where('id', id).update({
            dict_id: dictId,
            label: label,
            type: type,
            value: value,
            status: status,
            remark: remark,
        });
        ctx.success('', '修改成功');
    } catch (e: any) {
        ctx.fail(500, e.toString());
    }
    return next();
}

/**
 * @api {get} /dictItem/list 字典项列表
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen -> 全局查询字典
 * @apiName list
 * @apiGroup 字典项管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     type       字典类型【必填】
 *
 * @apiUse RequestHeader
 * @apiUse dictListSuccess
 * @apiUse RequestError
 */
async function listAction(ctx: Context, next: Next) {
    const { type } = ctx.query;
    try {
        const res = await knex('sys_dict_item').where({ type: type, status: '0' }).select();
        ctx.success(res, '查询成功');
    } catch (e: any) {
        ctx.fail(500, e.toString());
    }
    return next();
}

const dictItemController = {
    retrieveAction,
    addAction,
    deleteAction,
    updateAction,
    listAction,
};

export default dictItemController;
